<template>
  <div class="address-convergence">
    <!-- 汇聚地址 -->
    <div v-if="leftChecks" class="had-container" style="height: 100%;">
      <div class="c_top">
        <div class="text1">对象数：{{fileinfo.total_num}}</div>
        <div class="text1">目标地址：{{fileinfo.target_address_num}}</div>
        <div class="text2">系统根据上传文件的”地址“参数解析出目标地址，并将目标地址相同的对象汇聚到一起</div>
      </div>
      <div class="c_bottom">
        <div class="c_left">
          <div class="cl_top">
            <el-input
              size="mini"
              v-model="targetAddressKeyword"
              placeholder="搜索目标地址"
              @keyup.enter.native="targetAddressKeywordSearch"
              clearable
            >
              <el-button size="mini" @click="targetAddressKeywordSearch" slot="append">搜索</el-button>
            </el-input>
            <div class="t_title">
              <span>目标地址</span>
              <span>汇聚对象数</span>
            </div>
          </div>
          <div class="cl_list">
            <div
              class="cl_item"
              @click="clickclItem(item.id)"
              @dblclick="editTargetAddressShowFunc(item)"
              :class="item.selected ? 'cl_item_selected' : ''"
              v-for="item in leftChecks"
              :key="item.id"
            >
              <div class="cll_left">
                <el-checkbox v-model="item.isChecked"></el-checkbox>
                <span class="text_overflow">{{ item.target_address || '空地址' }}</span>
              </div>
              <div style="display:flex;justify-content: flex-start;align-items:center;">
                <span>{{ item.count }}</span>
                <i
                  class="el-icon-edit-outline"
                  @click.stop="editTargetAddressShowFunc(item)"
                  style="margin-left:6px"
                ></i>
              </div>
            </div>
          </div>
          <div class="cl-bottom">
            <div class="clb-left">
              <span class="clb-choose" v-if="leftCheckIds.length > 0">
                已选择
                <span style="color: #E6A23C">{{leftCheckIds.length}}</span>项
              </span>
              <div>
                <el-button type="primary" size="mini" class="hebing-btn" @click="mergeBtnClick">合并</el-button>
                <el-button
                  type="text"
                  size="mini"
                  class="h-clear"
                  v-if="leftCheckIds.length"
                  @click="clearLeftChecksFunc()"
                >清空</el-button>
              </div>
            </div>
            <el-pagination
              :pager-count="5"
              small
              layout="prev, pager, next"
              :total="leftPager.total_num"
              @current-change="leftPageChange"
            ></el-pagination>
          </div>
        </div>
        <div class="c_right">
          <el-table :data="tableData" @selection-change="rightHandleSelectionChange" ref="multipleTable"  border stripe row-key="tableKey">
            <el-table-column type="selection" width="55" reserve-selection></el-table-column>
            <el-table-column prop="obj_number" label="对象编号"></el-table-column>
            <el-table-column prop="obj_name" label="对象名称" show-overflow-tooltip></el-table-column>
            <el-table-column prop="source_address" label="源地址" show-overflow-tooltip></el-table-column>
            <el-table-column prop="details" label="详情" show-overflow-tooltip>></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="editAddressShowFunc([scope.row.id])"
                >更改目标地址</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="cr-bottom">
            <div class="crb-left">
              <el-button
                type="primary"
                size="mini"
                @click="editAddressShowFunc(rightMultipleSelection)"
              >更改目标地址</el-button>
              <span
                class="clb-choose"
                style="margin-left: 6px;"
                v-if="rightMultipleSelection.length > 0"
              >
                已选择
                <span style="color: #E6A23C">{{rightMultipleSelection.length}}</span>项
              </span>
            </div>
            <el-pagination
              small
              layout="prev, pager, next"
              @current-change="pageChange"
              :total="rightPager.total_num"
            ></el-pagination>
          </div>
        </div>

        <!-- 更改目标地址 dialog editAddressDialogShow -->
        <addrChangeWin
          :visible.sync="editAddressDialogShow"
          :onOk="(e) => {closeDialog('editAddressDialogShow', e);getTargetDetailList();initTableData();}"
          :names="targetOldAddrNames"
          :tarAddrOptions="targetOptions"
          ref="addrChangeWinRef"
        ></addrChangeWin>
      </div>
    </div>
    <!-- 空数据的时候 -->
    <div class="no_data" v-else>
      <img class="pic" :src="noData" alt="noData" />
      <span style="font-weight: 800;font-size:16px;margin: 10px 0;">暂无数据</span>
      <span style="margin: 5px 0;">导入文件后</span>
      <span>
        点击文件后的”
        <span class="color1" @click="gotoFileList">启动地址处理</span>“按钮
      </span>
      <span>即可开始地址处理</span>
    </div>

    <!-- 合并目标地址的 dialog mergeAddressDialogShow -->
    <addrMergeWin
      :visible.sync="mergeAddressDialogShow"
      :onOk="(e) => {closeDialog('mergeAddressDialogShow', e);initTableData()}"
      :checks="mergeAddressFormChecks"
      :mergeAddressOptions="mergeAddressOptions"
    ></addrMergeWin>

    <!-- 修改目标地址 dialog editTargetAddressShowDialog -->
    <addrEditWin
      :visible.sync="editTargetAddressShowDialog"
      :onOk="(e) => closeDialog('editTargetAddressShowDialog', e)"
      :confirmSubmit="confirmEditTargetAddressFunc"
      :oldAddr="leftFormData.oldAddr"
    ></addrEditWin>
  </div>
</template>
<script>
import noData from "@/icons/noData.svg";
import addrChangeWin from "./addrCollect/addrChangeWin";
import addrEditWin from "./addrCollect/addrEditWin";
import addrMergeWin from "./addrCollect/addrMergeWin";

import { addOperationLog } from "@/utils/index";
// import addrMergePreWin from "./addrCollect/addrMergePreWin";

export default {
  components: {
    addrChangeWin,
    addrEditWin,
    addrMergeWin,
    // addrMergePreWin,
  },
  data() {
    return {
      noData: noData,
      showMergeSuccess: false,
      targetOldAddrNames: [],
      targetOptions: [],
      leftChecks: [],
      leftFormData: {
        oldAddr: "",
        newAddr: "",
      },
      rightPager: {
        page: 1,
        limit: 10,
        total_num: 0,
      },
      leftPager: {
        page: 1,
        limit: 10,
        total_num: 0,
      },
      mergeAddressDialogShow: false,
      addrMergePreWinShow: false,
      rightMultipleSelection: [],
      tableData: [],
      editAddressDialogShow: false,
      editTargetAddressShowDialog: false,
      mergeAddressFormChecks: [],
      targetAddressKeyword: "",
      currentLeftItem: {},
      mergeAddressOptions: [],
      fileinfo: {},
      leftTotalDatas: [],
      checksInLocal: [],
      isClickItemLoading: false
    };
  },
  mounted() {
    this.initTableData();
    this.getTargetDetailList();
  },
  methods: {
    gotoFileList(){
      this.$router.push('/fileList')
    },
    async initTableData() {

      const res = await this.axios.post(
        this.apis.addressDataGroupingStatistics,
        {
          target_address: this.targetAddressKeyword || undefined,
          import_file_record_id: this.$store.state.currentFileInfo.id,
        }
      );
      console.log("获取左边的数据res:", res);
      if (res.retCode === 2000) {
        this.leftTotalDatas = res.rows.items;

        this.leftChecks = JSON.parse(JSON.stringify(this.leftTotalDatas))
          .splice((this.leftPager.page - 1) * 10, 10)
          .map((item, i) => ({
            ...item,
            selected: false,
            id: new Date().getTime() + i,
            isChecked: (this.getCheckLocal())[item.target_address] || false,
          }));

        this.leftPager.total_num = res.rows.target_address_num;
        this.fileinfo = {
          total_num: res.rows.total_num,
          target_address_num: res.rows.target_address_num,
        };
        this.currentLeftItem = this.leftChecks[0] || {};

        this.currentLeftItem.selected = true;
        // res.rows.items = JSON.parse(JSON.stringify(res.rows.items)).splice((0 - 1 + this.leftPager.page) * 10, 10 * this.leftPager.page)
      }else{
        this.leftChecks = []
      }

      // this.getTargetDetailList();
    },
    leftPageChange(e) {
      console.log(e, "e");
      this.leftPager.page = e;
      this.leftChecks = JSON.parse(JSON.stringify(this.leftTotalDatas))
        .splice((e - 1) * 10, 10)
        .map((item, i) => ({
          ...item,
          selected: false,
          id: new Date().getTime() + i,
          isChecked: (this.getCheckLocal())[item.target_address],
        }));

      console.log(this.leftTotalDatas, "leftTotalDatas");
    },
    async getTargetDetailList() {
      const res2 = await this.axios.post(this.apis.addressDataQuery, {
        import_file_record_id: this.$store.state.currentFileInfo.id,
        target_address: this.currentLeftItem.target_address || undefined,
        page: this.rightPager.page,
        limit: 10,
      });
      console.log("获取右边边的数据res2:", res2);
      if (res2.retCode === 2000) {
        this.tableData = res2.rows.items;
        this.rightPager.total_num = res2.rows.total_num;
        this.$refs.multipleTable.clearSelection();
      }
    },
    mergeBtnClick() {
      if (!this.leftCheckIds.length) {
        this.$message.warning("请先选择目标地址！");
        return;
      }
      this.mergeAddressDialogShow = true;
      this.mergeAddressOptions = this.leftCheckIds.map((item) => ({
        value: item,
        label: item,
      }));
      this.mergeAddressFormChecks = this.leftCheckIds;
    },
    getCheckLocal(){
      console.log(JSON.parse(localStorage.getItem('checksInLocal')), 'JSON.parse');
      return JSON.parse(localStorage.getItem('checksInLocal')) || {}
    },
    getLeftChecks(){
      return JSON.parse(localStorage.getItem('ckids')) || []
    },
    setCheckLocalAndCheckids(tAddrMaps, ckidMaps){
      // 存进缓存，为历史记录做处理。
      let checksInLocal = this.getCheckLocal() 
      this.checksInLocal = {...checksInLocal, ...tAddrMaps}
      localStorage.setItem('checksInLocal', JSON.stringify({...checksInLocal, ...tAddrMaps}))
    },
    clickclItem(id) {
      // 防止多次点击
      // if (this.isClickItemLoading) {
      //   return
      // }
      // setTimeout(() => {
      //   this.isClickItemLoading = false
      // }, 1000);
      // this.isClickItemLoading = true

      // console.log('isClickItemLoading');

      this.leftChecks.forEach((item) => {
        if (item.id === id) {
          this.currentLeftItem = item;
          item.selected = !item.selected;
        } else {
          item.selected = false;
        }
      });

      // this.initTableData();

      // setTimeout(() => {
      //   console.log(this.leftCheckIds);
      // }, 1000);
    },
    pageChange(e) {
      this.rightPager.page = e;
      this.getTargetDetailList();
    },
    closeDialog(dialogStr) {
      this[dialogStr] = false;
    },
    editAddressShowFunc(ids) {
      if (!ids.length) {
        this.$message.warning("请先选择想要更改的对象");
        return;
      }
      
      this.$refs.addrChangeWinRef.editIds = ids
      this.editAddressDialogShow = true;
      let names = [];
      this.tableData.forEach((it1) => {
        ids.forEach((it2) => {
          if (it1.id === it2) {
            names.push(it1.target_address);
          }
        });
      });
      console.log(names, "mnames");
      this.targetOldAddrNames = names;
      this.targetOptions = JSON.parse(JSON.stringify(this.leftTotalDatas))
      console.log(ids);
    },
    targetAddressKeywordSearch() {
      // if (!this.targetAddressKeyword) {
      //   this.$message.warning("请输入");
      //   return;
      // }
      this.initTableData();
    },
    editTargetAddressShowFunc(item) {
      console.log(item, "editTargetAddressShowFunc");
      this.leftFormData.oldAddr = item.target_address;
      console.log(this.leftFormData, "leftFormData");
      this.editTargetAddressShowDialog = true;
    },
    async confirmEditTargetAddressFunc(newAddr, oldAddr) {
      console.log(newAddr, oldAddr);
      const res = await this.axios.post(
        this.apis.addressDataUpdateTargetAddress,
        {
          import_file_record_id: Number(this.$store.state.currentFileInfo.id),
          old_target_address: [oldAddr],
          new_target_address: newAddr,
        }
      );
      if (res.retCode === 2000) {
        this.$message.success("修改成功!");
        // this.initTableData();
        this.leftChecks = this.leftChecks.map(item => ({
          ...item,
          target_address: item.target_address == oldAddr ? newAddr : item.target_address
        }))
        // console.log(this.leftChecks, 'this.leftChecks');
        this.rightPager.page = 1;

        await addOperationLog({ 
          title: "修改目标地址",
          content: {
            old_target_address: [oldAddr],
            new_target_address: newAddr,
          },
        });
      }
    },
    rightHandleSelectionChange(val) {
      console.log(val, "val");
      this.rightMultipleSelection = val.map((item) => item.id);
    },
    clearLeftChecksFunc() {
      this.leftChecks.forEach(item => {
        item.isChecked = false
      })
      localStorage.removeItem('checksInLocal')
      this.checksInLocal = {}
    },
  },
  watch: {
    leftChecks: {
      handler(val) {
        let checksTargetMap = {}
        val.forEach((item) => {
          if (item.isChecked) {
            checksTargetMap[item.target_address] = true
          }else{
            checksTargetMap[item.target_address] = false
          }
        });
        this.setCheckLocalAndCheckids(checksTargetMap)
      },
      deep: true,
    },
    getCurrentFileInfo: function (val, oldval) {
      console.log("currentFileInfo变化了", val, oldval);
      // if (JSON.stringify(val) !== JSON.stringify(oldval)) {
      // console.log('change currentFileInfo变化了');
      this.initTableData();
      this.getTargetDetailList();
      // }
    },
    currentLeftItem: {
      handler(val, oldval) {
        if (JSON.stringify(val) != JSON.stringify(oldval)) {
          console.log("tersts");
          this.getTargetDetailList();
        }
      },
      deep: true,
    },
    leftTotalDatas: function (val) {
      this.$store.state.leftChecks = val
    }
  },
  computed: {
    getCurrentFileInfo() {
      return this.$store.state.currentFileInfo;
    },
    leftCheckIds: function() {
      let arr = []
      console.log(this.checksInLocal, 'Object.keys(this.checksInLocal)');
      Object.keys(this.checksInLocal).forEach(key => {
        console.log(key, 'key');
        if(this.leftChecks.map(item => item.target_address).includes(key) && this.checksInLocal[key]){
          arr.push(key)
        }
      })
      return arr
    }
  },
};
</script>
<style lang="less">
.no_data {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  margin-top: 150px;
  align-items: center;
  font-size: 14px;
  line-height: 20px;
  .pic {
    width: 72px;
    height: 72px;
  }

  .color1 {
    color: rgba(37, 158, 234, 1);
    cursor: pointer;
  }
}
.container {
}
.c_top {
  background-color: #d3e7ff;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 10px 10px;
  border-radius: 2px;
}
.text1 {
  font-size: 12px;
  font-weight: 600;
}
.text1:nth-child(2) {
  margin-left: 20px;
}
.text2 {
  margin-left: 20px;
  font-size: 10px;
}

.c_left {
  width: 300px;
  max-width: 330px;
  border: 1px solid #ececec;
  background: #f2f2f2;
  box-sizing: border-box;
  position: relative;
}
.cl_top {
  font-size: 12px;
  color: #444444;
  padding: 20px 10px 0 10px;
  .t_title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20px 0 3px 0;
    padding: 0 20px;
    font-size: 12px;
    font-weight: bold;
  }
}
.cl_list {
  /* border: 1px solid #ececec; */
  font-size: 10px;
}
.cl_item:hover,
.cl_item_selected {
  background: #fff;
  border: 1px solid #ececec;
  transform: translateX(1px);
  color: #409eff;
}

.cl_item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 10px;
  border: 1px solid transparent;
  cursor: pointer;
}
.el {
}
.text_overflow {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 200px;
  margin-left: 10px;
}
.cll_left {
  display: flex;
  justify-content: flex-start;
}

.cl_top .el-input__inner {
  padding: 0 8px;
}

.cl_top .el-input-group__append span {
  font-weight: 400;
}
.cl_top .el-input-group__append,
.el-input-group__prepend {
  background-color: rgba(30, 141, 225, 1);
  color: #fff;
}

.cl_top .el-button--mini,
.el-button--mini.is-round {
  padding-left: 10px;
  padding-right: 10px;
}

.c_bottom {
  display: flex;
  flex: 1;
}
.c_right {
  flex: 1;
  padding: 10px;
  position: relative;
  padding-bottom: 150px;
  overflow: hidden;
}

.c_right .el-table__header-wrapper .el-table__cell {
  padding: 5px 0;
  font-size: 12px;
}
.c_right .el-table__body-wrapper .el-table__cell {
  padding: 5px 0;
  font-size: 10px;
}

.c_right th.el-table__cell {
  background-color: rgba(245, 247, 250, 1);
}

.c_bottom .el-dialog__body {
  padding-top: 10px;
}

.c_bottom .el-dialog__body .el-form-item__label {
  font-size: 12px;
}

.c_bottom .el-dialog__body .el-form-item {
  margin-bottom: 0px;
}
.c_bottom .el-dialog__body .el-form-item .el-input input {
  padding-left: 5px;
}

.c_bottom .el-dialog__body .el-form-item__label {
  font-size: 12px;
}

.c_bottom .el-dialog__header {
  border-bottom: #ececec 1px solid;
  padding: 10px 20px;
}
.c_bottom .el-dialog__title {
  font-size: 14px;
  font-weight: 600;
}

.select_search input:valid {
  border: none;
}
.select_search input:focus {
  border: none;
  outline: none;
}
.select_search input {
  padding-left: 30px !important;
  background-color: #f2f2f2;
}
.select_box {
  background-color: #fff;
  padding: 4px 16px;
  position: absolute;
  top: 40px;
  left: 0;
  z-index: 1000;
  border: 1px solid #ececec;
  border-radius: 2px;
  width: 100%;
  box-sizing: border-box;
}
.result_list {
}
.result_item:hover {
  background-color: rgba(241, 249, 254, 1);
}
.result_item {
  font-size: 12px;
  color: #444444;
  cursor: pointer;
  padding: 4px 0;
  line-height: 20px;
}
.search_result_wrapper {
  overflow-y: auto;
  height: 140px;
}

.had-container {
  border: 1px solid #ececec;
  display: flex;
  flex-direction: column;
}

.cl-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 6px;
  background-color: #fff;
  border-top: 1px solid #ececec;
  position: absolute;
  bottom: 0;
  width: 100%;
  box-sizing: border-box;
}

.clb-left {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
}
.hebing-btn {
  padding: 3px 5px !important;
}
.h-clear {
  margin-left: 3px !important;
}
.clb-choose {
  font-size: 12px;
  /* margin-left: 0px; */
  margin-bottom: 5px;
}
.cl-bottom .el-pager li.active {
  background-color: #409eff;
  border-radius: 3px;
  color: #fff;
}
.cl-bottom .el-pagination .btn-prev,
.cl-bottom .el-pagination .btn-next {
  padding: 0 4px !important;
}
.cl-bottom .el-pager li {
  padding: 0;
  width: 1rem;
}
.cr-bottom {
  margin-top: 20px;
  padding: 10px 0;
  border-top: 1px solid #ececec;
  position: absolute;
  bottom: 0;
  width: 100%;
  z-index: 99;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
/* .cr-bottom  */
.cr-bottom .el-pager li.active {
  background-color: #409eff;
  border-radius: 3px;
  color: #fff;
}
.textyc {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.address-convergence {
  height: 100%;
}

.merge-address_dialog .el-dialog__title {
  font-size: 14px;
  font-weight: 600;
}
.merge-address_dialog .el-dialog__header {
  border-bottom: #ececec 1px solid;
  padding: 10px 20px;
}

.merge-address_dialog .el-dialog__body {
  padding: 20px;
}

.merge-address_dialog .el-icon-close {
  /* display: none; */
}
.merge-tips {
  margin-top: 80px;
  font-size: 12px;
}
.merge-tips .tips-item {
  transform: translateX(30px);
  margin-bottom: 10px;
}
</style>

